﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace library.core
{
    class DataIntegrity
    {

        #region Thread Refresh

        static Thread thread;

        internal static void Start()
        {
            thread = new Thread(new ThreadStart(Load));

            thread.Start();
        }

        internal static void Stop()
        {
            thread.Abort();
        }

        static List<DataIntegrityObject> items = new List<DataIntegrityObject>();

        internal static void Load()
        {
            if (!File.Exists(Parameters.localDataIntegrity))
            {
                byte[] buffer = File.ReadAllBytes(Parameters.localDataIntegrity);

                int offset = 0;
            }

            ThreadRefresh();
        }

        static void ThreadRefresh()
        {
            while (true)
            {
                Thread.Sleep(Parameters.refreshData);

                Refresh();
            }
        }

        static void Refresh()
        {
            if (addresses.Count() > 0)
            {
                IOrderedEnumerable<byte[]> addresses_refresh = addresses.OrderBy(x => Utils.Rand.Next() - .5);

                IEnumerable<byte[]> addresses_refresh_list = addresses_refresh.Take(Parameters.dataPerRefresh);

                foreach (byte[] address in addresses_refresh_list)
                {
                    p2pRequest.Send(
                        address: address,
                        data: Get(address));

                    Thread.Sleep(10);
                }

                addresses_refresh = addresses.OrderBy(x => Parameters.addressSize - Addresses.Compare(Client.localPeer.Address, x));

                addresses_refresh_list = addresses_refresh.Take(Parameters.dataPerRefresh);

                int totalRemoved = 0;

                foreach (byte[] address in addresses_refresh_list)
                {
                    if (totalRemoved < Parameters.maxDataAddressRemovedPerRefresh && addresses.Count() > Parameters.maxDataAddress)
                    {
                        addresses.Remove(address);

                        File.Delete(Path.Combine(Parameters.localData, string.Join(".", address)));

                        totalRemoved++;
                    }

                    p2pRequest.Send(
                        address: address,
                        data: Get(address));

                    Thread.Sleep(10);
                }
            }
        }

        #endregion

    }

    class DataIntegrityObject
    {
        byte[] Address;
        byte[] Data;
        byte[] Actual;
        IPEndPoint EndPoint;
    }

}
